package com.lwlean.test.service.impl;


import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.lwlean.test.aliyun.oss.OSS;
import com.lwlean.test.service.OSSUploadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by lean on 2016/12/26.
 */
@Service
public class OSSUploadServiceImpl implements OSSUploadService {

    final private static Logger log = LoggerFactory.getLogger(OSSUploadServiceImpl.class);

//    @Value("${recordPath}")
    private String recordPath = "C:\\Users\\lean\\Desktop\\sharedfs\\record\\20161223";

//    @Value("${threadNum}")
    private int threadNum = 2;

    @Override
    public void ossUpload(OSS oss) {
        final OSSClient ossClient = oss.getOssClient();
        final String bucketName = oss.getBucket().getName();

        final List<String> list = new ArrayList<>();
        File file = new File(recordPath);
        if(file.isDirectory()){
            final File[] files = file.listFiles();
            addUrlToList(files,list);
        }

        ExecutorService executor = Executors.newFixedThreadPool(threadNum);
        for(int i=0;i<list.size();i++){
            final int finalI = i;
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    final String path = list.get(finalI);
                    log.info("get finalI:{} and path:{}",finalI,path);
                    final String key = "data/test/"+SubStrPath(path);
                    final String result = uploadObject2OSS(ossClient, new File(path), bucketName, key);
                    log.info("get result is :{}",result);
                }
            });
        }

        list.forEach(path->{
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    final String key = "data/test/"+SubStrPath(path);
                    final String result = uploadObject2OSS(ossClient, new File(path), bucketName, key);
                    log.info("get result is :{}",result);
                }
            });
        });
    }

    /**
     * 判断是否是语音文件，url放入list中
     * @param files
     * @param list
     */
    public void addUrlToList(File[] files,List<String> list){
        for(int i=0;i<files.length;i++){
            if(files[i].isDirectory()){
                final File[] subfiles = files[i].listFiles();
                addUrlToList(subfiles,list);
            }else{
                final String path = files[i].getPath();
                final String format = path.substring(path.lastIndexOf(".")+1);
                if("mp3".equals(format)){
                    list.add(path);
                }else{
                    log.error("this path is't mp3 file:{}",path);
                }
            }
        }
    }

    /**
     * 创建oss链接上传
     * @param ossClient
     * @param file
     * @param bucketName
     * @param key
     * @return
     */
    public String uploadObject2OSS(OSSClient ossClient, File file, String bucketName, String key){
        String resultString = null;
        try {
            InputStream is = new FileInputStream(file);
            final String fileName = file.getName();
            final long fileSize  = file.length();
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(is.available());
            metadata.setCacheControl("no-cache");
            metadata.setHeader("Pragma","no-cache");
            metadata.setContentEncoding("UTF-8");
            metadata.setContentType("application/octst-stream");
            metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
            final PutObjectResult putObjectResult = ossClient.putObject(bucketName, key, is, metadata);
            resultString = putObjectResult.getETag();
        } catch (Exception e) {
            log.error("upload faild in case :{}",e,e.getMessage());
        }
        return resultString;
    }

    public String SubStrPath(String path){
        final String[] paths = path.split("\\\\");
        final String filename = paths[paths.length - 1];
        final String accountSid = paths[paths.length - 2];
        final String date = paths[paths.length - 3];
        return date+"/"+accountSid+"/"+filename;
    }
}
